from sqlalchemy.orm import Session
from schema import Planting_Plan_schema
from model import Planting_Plan_model



def get_Planting_Plan(db: Session, ID: int):
    return db.query(Planting_Plan_model.Planting_plan).filter(Planting_Plan_model.Planting_plan.ID == ID).first()


def get_all_Planting_Plan(db: Session):
    return db.query(Planting_Plan_model.Planting_plan).all()


def delete_Planting_Plan(db: Session, ID):
    to_delete = db.query(Planting_Plan_model.Planting_plan).filter(Planting_Plan_model.Planting_plan.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Planting_Plan(db: Session, Planting_Plan: Planting_Plan_schema.Planting_plan):
    db_Planting_Plan = Planting_Plan_model.Planting_plan(
        PlanName=Planting_Plan.PlanName,
        CropHistoryID=Planting_Plan.CropHistoryID,
        StartDate=Planting_Plan.StartDate,
        EndDate=Planting_Plan.EndDate,
        PlanDuration=Planting_Plan.PlanDuration,
        PlotID=Planting_Plan.PlotID,
        Remarks=Planting_Plan.Remarks,
    )
    db.add(db_Planting_Plan)
    db.commit()
    db.refresh(db_Planting_Plan)
    return db_Planting_Plan


def update_Planting_Plan(db: Session, ID, field_name, new_value):
    db_Planting_Plan = db.query(Planting_Plan_model.Planting_plan).filter(Planting_Plan_model.Planting_plan.ID == ID).first()
    setattr(db_Planting_Plan, field_name, new_value)
    db.commit()
    db.refresh(db_Planting_Plan)
    return db_Planting_Plan
